package com.pine.dbant.core.config;


import com.pine.sunflower.core.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 统一响应包装器
 * Controller返回响应前，将响应对象用Result类包装
 * @Author: xiaoyuan
 * @Date: 2022/11/29 13:54
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@Slf4j
public class ResponseWrapperAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        final String returnTypeName = returnType.getParameterType().getName();
        return !(Result.class.getName().equals(returnTypeName)
                || ResponseEntity.class.getCanonicalName().equals(returnTypeName));
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType,
                                  MediaType contentType, Class<? extends HttpMessageConverter<?>> converterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        final String returnTypeName = returnType.getParameterType().getName();
        if (Void.class.getName().equals(returnTypeName)) {
            return Result.success();
        }
        if (!contentType.includes(MediaType.APPLICATION_JSON)) {
            // 返回值不要json
            return body;
        }
        if (Result.class.getName().equals(returnTypeName)) {
            return body;
        }
        return Result.success(body);
    }
}
